package com.springboot.middleware.middleware_lock.server.config;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryNTimes;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
public class ZooKeeperConfig {
    private static final Logger log = LoggerFactory.getLogger(ZooKeeperConfig.class);

    @Value("${zk.host}")
    private String connectString;
    @Value("${zk.namespace}")
    private String nameSpace;


    @Bean
    public CuratorFramework curatorFramework() {
        //创建CuratorFramework实例
        //1.创建的方式是采用工厂模式进行
        //2.指定了客户端连接到ZooKeeper服务端的策略, 这里是重试的机制(重连5次)
        log.info("注册zookeeper, connectString = {}, nameSpace = {}", connectString, nameSpace);
        CuratorFramework curatorFramework = CuratorFrameworkFactory.builder()
                .sessionTimeoutMs(10000)
                .connectString(connectString)
                .namespace(nameSpace)
                .retryPolicy(new RetryNTimes(5, 1000))
                .build();
        curatorFramework.start();
        log.info(String.valueOf(ZooKeeper.States.CONNECTED));
        return curatorFramework;
    }
}
